package cn.com.dhc.danlu.receiver;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import cn.com.dhc.danlu.activity.WelcomeActivity;
import cn.com.dhc.danlu.activity.message.MessageListActivity;
import cn.com.dhc.danlu.constant.MsgTypeConst;
import cn.com.dhc.danlu.constant.MsgTypeConst.MsgTypeGroup;
import cn.com.dhc.danlu.model.bus.MsgEvent;
import cn.com.dhc.danlu.model.bus.MsgEvent.MsgType;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.util.PushEngine;
import cn.com.hd.mall.web.webservices.entity.response.login.LoginResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author wuhaiyang
 */
public class MiPushReceiver extends PushMessageReceiver {
    public static MsgType globalType;
    public static boolean sIsLevelJump = false;

    @Override
    public void onReceivePassThroughMessage (Context context, MiPushMessage message) {
        super.onReceivePassThroughMessage (context, message);
    }

    @Override
    public void onNotificationMessageClicked (Context context, MiPushMessage message) {
        super.onNotificationMessageClicked (context, message);

        String content = message.getContent ();
        JSONObject jsonObject;
        String msgType = null;

        try {
            jsonObject = new JSONObject (content);
            msgType = jsonObject.getString ("msg_type");
        } catch (JSONException e) {
            e.printStackTrace ();
        }

        if (null != msgType) {
            if (null == DanluApplication.get () || null == agent.getLoginUser ()) {
                if (msgType.startsWith (MsgTypeGroup.PURCHASE_ORDER_MSG)) {
                    globalType = MsgType.ORDER_MSG;
                } else if (msgType.startsWith (MsgTypeConst.NOTICE) || msgType.startsWith (MsgTypeConst.OTHER)) {
                    globalType = MsgType.OHTER_MSG;
                }

                //依赖于 启动页去自动登陆
                sIsLevelJump = true;
                Intent intent = new Intent (context, WelcomeActivity.class);
                intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                context.startActivity (intent);
            } else {
                if (msgType.startsWith (MsgTypeGroup.PURCHASE_ORDER_MSG)) {
                    globalType = MsgType.ORDER_MSG;
                    toMsgActivity (context);
                } else if (msgType.startsWith (MsgTypeConst.OTHER) || msgType.startsWith (MsgTypeConst.NOTICE) || msgType.startsWith (MsgTypeGroup.DANLU_ENVELOP_MSG) || msgType.startsWith (MsgTypeGroup.DEALER_COUPON_MSG) || msgType.startsWith (MsgTypeGroup.DEALER_ENVELOP_MSG)) {
                    globalType = MsgType.OHTER_MSG;
                    toMsgActivity (context);
                }
            }
        }
    }

    @Override
    public void onNotificationMessageArrived (Context context, MiPushMessage message) {
        super.onNotificationMessageArrived (context, message);

        // 事件分发
        String content = message.getContent ();
        try {
            // 通知前台MainMenuActivity刷新底部角标数量
            JSONObject jsonObject = new JSONObject (content);
            int newCount = jsonObject.getInt ("msg_badge");
            // String msgType = jsonObject.getString ("msg_type");
            MsgEvent msgEvent = new MsgEvent ();
            msgEvent.setEventFrom (CommonConst.PushMsgFrom._FROM_PUSH_RECEIVER);
            msgEvent.setNewestCount (newCount);
            EventBus.getDefault ().post (msgEvent);
        } catch (Exception ignored) {
        }
    }

    @Override
    public void onReceiveRegisterResult (Context context, MiPushCommandMessage message) {
        String command = message.getCommand ();
        if (MiPushClient.COMMAND_REGISTER.equals (command)) {
            if (message.getResultCode () == ErrorCode.SUCCESS) {
                setAliasAndSubscribe ();
            }
        }
    }

    @Override
    public void onCommandResult (Context context, MiPushCommandMessage message) {
        String command = message.getCommand ();
        if (MiPushClient.COMMAND_REGISTER.equals (command)) {
            if (message.getResultCode () == ErrorCode.SUCCESS) {
                // 设置别名
                setAliasAndSubscribe ();
            }
        }

    }

    private void setAliasAndSubscribe () {
        LoginResponse user = agent.getLoginUser ();
        if (null != user && !TextUtils.isEmpty (user.getUserId ())) {
            PushEngine.newInstance ().setAlias (user.getUserId ());
            PushEngine.newInstance ().setTopic (CommonConst.TOPIC_PREFIX + agent.getLoginUser ().getCompanyId ());
        }
    }

    private void toMsgActivity (Context context) {
        // 由于消息中心暂时不需要token字段
        Intent intent = new Intent (context, MessageListActivity.class);
        intent.putExtra (MessageListActivity._TYPE_ADAPTER, globalType);
        intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity (intent);
    }
}